package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;

public class BetRequestHandler extends AbstractTableHandler {

	public BetRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		if(table.getGame() == null) {
			try {
				Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			}catch(Exception e){}
		} else {
			BetRequest ctr = (BetRequest)request;
			Client client = null;
			for(Client c : table.getPlayers()){
				if(c.getSocket().equals(socket)){
					client = c;
					break;
				}
			}
			
			if(table.getGame().newBet(client, ctr.getBet())){
				try {
					String[] param = new String[1]; param[0] = "OK /bet";
					Request r = new OKRequestFactory().build(param, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
			}
		}
	}

}
